package com.boarsoft.message.sofamq;

import java.util.Map.Entry;

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import com.boarsoft.message.core.MessageService;

/**
 * 基于SofaMQ客户端完成消息的外发<br>
 * 
 *
 * @author Mac_J
 *
 */
public class SofaMQClientEx extends SofaMQClient implements MessageService, ApplicationListener<ContextRefreshedEvent> {

	@Override
	public void init() {
		for (Entry<String, SofaMQDestination> en : destMap.entrySet()) {
			String key = en.getKey();
			SofaMQDestination dest = en.getValue();
			dest.setCode(key);
			// 初始化此队列的生产者
			SofaMQProducer producer = dest.getProducer();
			if (producer != null) {
				producer.init();
			}
		}
	}

	@Override
	public void put(com.boarsoft.message.bean.Message msg) throws Exception {
		SofaMQDestination dest = destMap.get(msg.getTarget());
		SofaMQProducerEx producer = (SofaMQProducerEx) dest.getProducer();
		producer.put(msg);
	}

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		// 容器初始化完成后的逻辑处理
		if (event.getApplicationContext().getParent() == null) {
			// 根应用上下文准备完成时会执行到这里
			// 可以在这里执行一些需要在容器完全初始化后执行的代码
			for (Entry<String, SofaMQDestination> en : destMap.entrySet()) {
				SofaMQDestination dest = en.getValue();
				// 初始化此队列的消费者
				SofaMQConsumer consumer = dest.getConsumer();
				if (consumer != null) {
					consumer.init(dest.getCode());
				}
			}
		}
	}
}